﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MSBTC.Model;
using MSBTC.ReportViewer;

namespace MSBTC.WinForms
{
    public partial class ProjectInfoForm : Form
    {
        MDIParent mdipar = new MDIParent();
        PMSContext dbcontext = new PMSContext();
        FormHelpers help = new FormHelpers();
        Project dbpj = new Project();
        private string Datamanip;
        private int rowselect;

        public ProjectInfoForm()
        {
            InitializeComponent();
        }

        private void ProjectInfoForm_Load(object sender, EventArgs e)
        {
            RefreshFields();
            RefreshDB();

            //retrieve all data of customers
            var cus = (from c in dbcontext.Customers
                       select c).ToList();
            if (cus != null)
            {
                foreach (var c in cus)
                {
                    //add customer name in combo box
                    cmbCname.Items.Add(c.Customer_Name.ToString());
                }
            }
            else
            {
                MessageBox.Show("There are no customer listed, please add customer in Customer Information in main menu", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        #region Functions
        private void RefreshDB()
        {
            //retrieve all data of projects in List
            var prj = (from c in dbcontext.Projects
                       select c).ToList();

            LVProjInfo.Items.Clear();
            if (prj.Count != 0)
            {
                foreach (var sqlPrj in prj)
                {
                    //add items in listview box
                    ListViewItem lvitems = LVProjInfo.Items.Add(sqlPrj.Projectid_PK.ToString());
                    lvitems.SubItems.Add(sqlPrj.Project_Name.ToString());
                    lvitems.SubItems.Add(sqlPrj.Description.ToString());
                    lvitems.SubItems.Add(sqlPrj.Location.ToString());
                    lvitems.SubItems.Add(sqlPrj.Budget.ToString());

                    var cus = dbcontext.Customers.Find(sqlPrj.Customerid_FK);
                    lvitems.SubItems.Add(cus.Customer_Name.ToString());
                }
            }
        }

        private void ClearFields()
        {
            txtID.Clear();
            txtPName.Clear();
            txtDesc.Clear();
            txtLocation.Clear();
            txtBudget.Clear();
            cmbCname.SelectedIndex = 0;
            txtSearch.Clear();

        }

        private void DisableFields()
        {
            txtID.Enabled = false;
            txtPName.Enabled = false;
            txtDesc.Enabled = false;
            txtLocation.Enabled = false;
            txtBudget.Enabled = false;
            cmbCname.Enabled = false;

        }

        private void EnableFields()
        {
            txtID.Enabled = true;
            txtPName.Enabled = true;
            txtDesc.Enabled = true;
            txtLocation.Enabled = true;
            txtBudget.Enabled = true;
            cmbCname.Enabled = true;
        }

        private void RefreshFields()
        {
            DisableFields();
            ClearFields();

            btnPrint.Enabled = false;
            btnNew.Enabled = true;
            btnDel.Enabled = false;
            btnEdit.Enabled = false;
            btnClear.Enabled = true;
            btnSave.Enabled = false;
        }
        #endregion

        private void btnClear_Click(object sender, EventArgs e)
        {
            ClearFields();
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            Datamanip = "Add";

            EnableFields();
            ClearFields();

            btnPrint.Enabled = false;
            btnSave.Enabled = true;
            btnNew.Enabled = false;
            btnEdit.Enabled = false;
            btnDel.Enabled = false;
            LVProjInfo.Enabled = false;
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            Datamanip = "Edit";

            EnableFields();

            btnSave.Enabled = true;
            btnNew.Enabled = false;
            btnDel.Enabled = false;
            btnEdit.Enabled = false;
            btnPrint.Enabled = false;
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            RefreshFields();
            LVProjInfo.Enabled = true;
        }

        #region  Save
        private void btnSave_Click(object sender, EventArgs e)
        {
            if ((txtPName.Text == null) || (txtLocation.Text == null) || (txtBudget.Text == null))
            {
                MessageBox.Show("Please fill up the missing fields", "Data Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else if (cmbCname.SelectedIndex == 0)
            {
                MessageBox.Show("Please select customer name", "Data Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else
            {

                if (Datamanip == "Add")
                {

                    var add = (from p in dbcontext.Projects
                               where p.Project_Name == txtPName.Text
                               select p).SingleOrDefault();

                    if (add == null)
                    {

                        dbpj.Project_Name = txtPName.Text;
                        dbpj.Description = txtDesc.Text;
                        dbpj.Location = txtLocation.Text;
                        dbpj.Budget = Convert.ToInt32(txtBudget.Text);
                        dbpj.Status = "Active";
                        var cid = (from c in dbcontext.Customers
                                   where c.Customer_Name == cmbCname.SelectedItem
                                   select c).SingleOrDefault();
                        dbpj.Customerid_FK = cid.Customerid_PK;

                        dbcontext.Entry(dbpj).State = EntityState.Added;
                        dbcontext.SaveChanges();


                        MessageBox.Show("Successfully Saved", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        RefreshFields();
                        RefreshDB();
                        return;
                    }

                    else
                    {
                        DialogResult YN = MessageBox.Show("Item already exist, do you want to replace it?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                        if (YN == DialogResult.Yes)
                        {
                            var replace = dbcontext.Projects.Find(add.Projectid_PK);

                            replace.Project_Name = txtPName.Text;
                            replace.Description = txtDesc.Text;
                            replace.Location = txtLocation.Text;
                            replace.Budget = Convert.ToInt32(txtBudget.Text);
                            replace.Status = "Active";

                            var cid = (from c in dbcontext.Customers
                                       where c.Customer_Name == cmbCname.SelectedItem
                                       select c).SingleOrDefault();
                            replace.Customerid_FK = cid.Customerid_PK;

                            dbcontext.Entry(replace).State = EntityState.Modified;
                            dbcontext.SaveChanges();

                            MessageBox.Show("Successfully Modified", "Modify", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            RefreshFields();
                            RefreshDB();
                            return;

                        }
                    }
                    LVProjInfo.Enabled = true;
                }

                else if (Datamanip == "Edit")
                {

                    /*TODO check for new item listed in the 2nd listbox that does not exist in the database.. and save
                    to database
                         
                    */
                    DialogResult YN = MessageBox.Show("Do you want to replace it?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                    if (YN == DialogResult.Yes)
                    {
                        #region editted items

                        var replace = dbcontext.Projects.Find(Convert.ToInt32(txtID.Text));

                        replace.Project_Name = txtPName.Text;
                        replace.Description = txtDesc.Text;
                        replace.Location = txtLocation.Text;
                        replace.Budget = Convert.ToInt32(txtBudget.Text);
                        replace.Status = "Active";

                        var cid = (from c in dbcontext.Customers
                                   where c.Customer_Name == cmbCname.SelectedItem
                                   select c).SingleOrDefault();
                        replace.Customerid_FK = cid.Customerid_PK;

                        dbcontext.Entry(replace).State = EntityState.Modified;
                        dbcontext.SaveChanges();

                        MessageBox.Show("Successfully Modified", "Modify", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        RefreshFields();
                        RefreshDB();

                        #endregion
                    }
                }
            }
        }
       
        #endregion

        private void LVProjInfo_SelectedIndexChanged(object sender, EventArgs e)
        {
            //focus the selected items
            rowselect = LVProjInfo.FocusedItem.Index;
            
            //getting the information from the listview to textbox
            txtID.Text = LVProjInfo.Items[rowselect].SubItems[0].Text;
            txtPName.Text = LVProjInfo.Items[rowselect].SubItems[1].Text;
            txtDesc.Text = LVProjInfo.Items[rowselect].SubItems[2].Text;
            txtLocation.Text = LVProjInfo.Items[rowselect].SubItems[3].Text;
            txtBudget.Text = LVProjInfo.Items[rowselect].SubItems[4].Text;
            cmbCname.SelectedItem = LVProjInfo.Items[rowselect].SubItems[5].Text;

            help.getPname(txtPName.Text);

            btnDel.Enabled = true;
            btnEdit.Enabled = true;
            btnNew.Enabled = true;
            btnSave.Enabled = false;
            btnPrint.Enabled = true;
        }

        private void btnDel_Click(object sender, EventArgs e)
        {
            DialogResult YN = MessageBox.Show("There are some records will affect this delete, Do you still want to proceed?", "Deleting", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (YN == DialogResult.Yes)
            {
                var del = dbcontext.Projects.Find(Convert.ToInt32(txtID.Text));//get the same ID of purchase order to delete
                if (del != null)
                {
                    var labr = (from l in dbcontext.Labors
                                where l.Projectid_FK == del.Projectid_PK
                                select l).ToList();
                    if (labr.Count != 0)
                    {
                        foreach (var itm in labr)
                        {
                            //delete each laborer
                            dbcontext.Entry(itm).State = EntityState.Deleted;
                            dbcontext.SaveChanges();
                            
                        }
                        MessageBox.Show("Laborer deleted");
                    }

                    var prjeq = (from pe in dbcontext.PrjEqs
                                 where pe.Projectid_FK == del.Projectid_PK
                                 select pe).ToList();
                    if (prjeq.Count != 0)
                    {
                        foreach (var itm in prjeq)
                        {
                            var equip = dbcontext.Equipments.Find(itm.Equipid_FK);
                            equip.QtyUsed -= itm.QuantityUsed;

                            dbcontext.Entry(equip).State = EntityState.Modified;
                            dbcontext.Entry(itm).State = EntityState.Deleted;
                            dbcontext.SaveChanges();
                        }
                        MessageBox.Show("Project-Equipment deleted");
                    }

                    var matest = (from m in dbcontext.Materials
                                  where m.Projectid_FK == del.Projectid_PK
                                  select m).ToList();
                    if (matest.Count != 0)
                    {
                        foreach (var itm in matest)
                        {
                            dbcontext.Entry(itm).State = EntityState.Deleted;
                            dbcontext.SaveChanges();
                        }
                        MessageBox.Show("Materials Estimation deleted");
                    }
                    //delete the ID selected
                    dbcontext.Entry(del).State = EntityState.Deleted;
                    dbcontext.SaveChanges();
                }
                RefreshFields();
                RefreshDB();
            }
        }

        private void txtSearch_TextChanged(object sender, EventArgs e)
        {
            if (txtSearch.Text == "")
            {
                RefreshDB();
            }
            else
            {
                //retrieve the same item name search by user
                var proj = (from p in dbcontext.Projects
                           where p.Project_Name.Contains(txtSearch.Text)
                           select p).ToList();

                LVProjInfo.Items.Clear();
                if (proj.Count != 0)
                {

                    {
                        foreach (var sqlpj in proj)
                        {
                            ListViewItem lvitems = LVProjInfo.Items.Add(sqlpj.Projectid_PK.ToString());
                            lvitems.SubItems.Add(sqlpj.Project_Name.ToString());
                            lvitems.SubItems.Add(sqlpj.Description.ToString());
                            lvitems.SubItems.Add(sqlpj.Location.ToString());
                            lvitems.SubItems.Add(sqlpj.Budget.ToString());

                            var clnt = dbcontext.Customers.Find(sqlpj.Customerid_FK);
                            lvitems.SubItems.Add(clnt.Customer_Name);

                        }
                    }
                }

            }
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            help.GetPrintStat("nALL");

            ProjRptForm pjrpt = new ProjRptForm();

            pjrpt.Show();
        }

        private void btnPAll_Click(object sender, EventArgs e)
        {
            help.GetPrintStat("ALL");

            ProjRptForm pjrpt = new ProjRptForm();

            pjrpt.Show();
        }

    }
 }
